package ee.ttu.lecturerate;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import ee.ttu.lecturerate.data.Comment;
import ee.ttu.lecturerate.data.Lecture;
import ee.ttu.lecturerate.http.AsyncTaskExecutor;
import ee.ttu.lecturerate.http.RequestAssembler;
import ee.ttu.lecturerate.http.RequestInput;
import android.os.Bundle;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;

public class LectureView extends ListActivity {
	
	private Lecture activeLecture;
	private CommentAdapter commentAdapter;
	private Timer autoupdate;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		Log.d("LectureView.onCreate()", "LectureView activity started");
		
		loadContents(getIntent(), false);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_lecture_view, menu);
		return true;
	}
	
	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		
		Log.d("LectureView.onNewIntent()", "new intent received");
		
		//TODO: probably this doesn't work as intended, but by chance it doesn't need to
		loadContents(intent, true);
	}
	
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		
		if(position == 0){
			if(activeLecture != null) {
				Intent intent = new Intent(v.getContext(), RateActivity.class);
				intent.putExtra("lectureId", String.valueOf(activeLecture.getId()));
				startActivity(intent);
			}
		}
		super.onListItemClick(l, v, position, id);
	}
	
	private void loadContents(Intent intent, boolean isReload)
	{
		List<Comment> commentList = (ArrayList<Comment>) intent.getSerializableExtra("comments");
		
		float averageRating = intent.getFloatExtra("average_rating", 0);
		
		Lecture lecture = (Lecture) intent.getSerializableExtra("lecture");
		activeLecture = lecture;
				
		//get header
		LayoutInflater inflater = LayoutInflater.from(this);
		View headerView = inflater.inflate(R.layout.activity_lecture_view, null);
				
		TextView titleTextView = (TextView) headerView.findViewById(R.id.lectureTitle);
		titleTextView.setText(lecture.getName());
			
		TextView lecturerTextView = (TextView) headerView.findViewById(R.id.lecturer);
		lecturerTextView.setText(lecture.getLecturer());
			
		TextView locationTextView = (TextView) headerView.findViewById(R.id.lectureLocation);
		locationTextView.setText(lecture.getLocation());
			
		TextView descriptionTextView = (TextView) headerView.findViewById(R.id.lectureDescription);
		descriptionTextView.setText(lecture.getDescription());
			
		TextView durationTextView = (TextView) headerView.findViewById(R.id.lectureDuration);
		durationTextView.setText(String.valueOf(lecture.getDuration()) + "min");
			
		SimpleDateFormat sdf = new SimpleDateFormat("hh:mm dd/MM/yy");
		TextView dateTextView = (TextView) headerView.findViewById(R.id.lectureDate);
		dateTextView.setText(sdf.format(lecture.getDate()));
			
		RatingBar ratingBar = (RatingBar) headerView.findViewById(R.id.lectureRating);
		ratingBar.setRating(averageRating);	
		
		if(isReload) {
			commentAdapter.clear();
			for(Comment comment : commentList) {
				commentAdapter.add(comment);
			}
			commentAdapter.notifyDataSetChanged();
		}
		else {
			getListView().addHeaderView(headerView);
			commentAdapter = new CommentAdapter(this, 
					R.layout.comment_list_item, commentList);
			getListView().setAdapter(commentAdapter);
		}
		
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		//autoupdate = new Timer();
		//autoupdate.schedule(new AutoUpdateTimerTask(), 5000, 10000);
	}

	@Override
	protected void onPause() {
		//autoupdate.cancel();
		super.onPause();
	}

	class CommentAdapter extends ArrayAdapter<Comment>
	{
		private int resource;
		private LayoutInflater inflater;
		
		public CommentAdapter(Context context, int textViewResourceId,
				List<Comment> commentList) {
			super(context, textViewResourceId, commentList);
			
			this.resource = textViewResourceId;
			this.inflater = LayoutInflater.from(context);	
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent)
		{
			convertView = (LinearLayout) inflater.inflate(resource, null);
			
			TextView authorTextView = (TextView) convertView.findViewById(R.id.commentAuthor);
			TextView dateTextView = (TextView) convertView.findViewById(R.id.commentDate);
			TextView commentTextView = (TextView) convertView.findViewById(R.id.comment);
			RatingBar ratingBar = (RatingBar) convertView.findViewById(R.id.commentRating);
			
			Comment comment = getItem(position);
			
			//convertView.setId(comment.getId());
			authorTextView.setText(comment.getAuthor());
			commentTextView.setText(comment.getComment());
			ratingBar.setRating(comment.getRating());
			
			SimpleDateFormat sdf = new SimpleDateFormat("hh:mm dd/MM/yy");
			String dateString = sdf.format(comment.getDate());
								
			dateTextView.setText(dateString);
			
			return convertView;
		}
		
	}
	
	class AutoUpdateTimerTask extends TimerTask
	{

		@Override
		public void run() {
			
			runOnUiThread(new AutoUpdateRunnable());
		}
		
		class AutoUpdateRunnable implements Runnable
		{
			@Override
			public void run() {
				List<RequestInput> inputList = new ArrayList<RequestInput>();
				RequestInput input1 = 
						RequestAssembler.assembleGetLecture(String.valueOf(activeLecture.getId()));
		    	inputList.add(input1);
		    	RequestInput input2 = 
		    			RequestAssembler.assembleGetCommentsByLecture(String.valueOf(activeLecture.getId()));
		    	inputList.add(input2);
		    	
		    	AsyncTaskExecutor executor = new AsyncTaskExecutor(inputList, LectureView.this);
		    	executor.execute();
				
			}
			
		}
		
	}

}
